/*
 * Copyright 2007 The semap project development team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Created by dulanov at Nov 26, 2007 5:16:52 AM.
 *
 * $Id: SPARQLResultsTSVWriter.java 856 2007-11-29 08:56:56Z dulanov $
 */

package net.sf.semap.sandbox.sesame.resultio.sparqltsv;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openrdf.model.BNode;
import org.openrdf.model.Literal;
import org.openrdf.model.Value;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.TupleQueryResultHandlerException;
import org.openrdf.query.resultio.TupleQueryResultFormat;
import org.openrdf.query.resultio.TupleQueryResultWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Writes SPARQL tuple query results in the <a
 * href="http://www.iana.org/assignments/media-types/text/tab-separated-values">Tab Separated Values Format</a>.
 *
 * @author <a href="mailto:dulanov@gmail.com">dulanov</a>
 * @version $Id: SPARQLResultsTSVWriter.java 856 2007-11-29 08:56:56Z dulanov $
 */
public class SPARQLResultsTSVWriter implements TupleQueryResultWriter {

	private static final Logger logger = LoggerFactory.getLogger(SPARQLResultsTSVWriter.class);

	private Writer writer;
	private List<String> bindingNames;

	public SPARQLResultsTSVWriter(OutputStream out) {
		this(new OutputStreamWriter(out, Charset.forName("UTF-8")));
	}

	public SPARQLResultsTSVWriter(Writer writer) {
		this.writer = writer;
	}

    @Override public TupleQueryResultFormat getTupleQueryResultFormat() {
	    return new TupleQueryResultFormat("SPARQL/TSV", "text/tab-separated-values", Charset.forName("UTF-8"), "tsv");
    }

	@Override public void startQueryResult(List<String> bindingNames) throws TupleQueryResultHandlerException {
		this.bindingNames = bindingNames;
		StringBuilder builder = new StringBuilder();
		for (String name : bindingNames) {
			builder.append(name).append("\t");
		}
		writeAndFlush(builder.deleteCharAt(builder.length() - 1).toString());
	}

	@Override public void endQueryResult() throws TupleQueryResultHandlerException {
	}

	@Override public void handleSolution(BindingSet bindingSet) throws TupleQueryResultHandlerException {
		Map<String, String> representation = new HashMap<String, String>(bindingNames.size());
		for (Binding binding : bindingSet) {
			String name = binding.getName();
			Value value = binding.getValue();
			if (value instanceof BNode) {
				representation.put(name, "_:" + value.stringValue());
			} else if (value instanceof Literal) {
				representation.put(name, value.stringValue() + (null != ((Literal) value).getLanguage() ? "@" + ((Literal) value).getLanguage() : ""));
			} else {
				representation.put(name, value.stringValue());
			}
		}

		StringBuilder builder = new StringBuilder("\n");
		for (String name : bindingNames) {
			builder.append(representation.containsKey(name) ? representation.get(name) : "").append("\t");
		}
		writeAndFlush(builder.deleteCharAt(builder.length() - 1).toString());
	}

    private void writeAndFlush(String str) throws TupleQueryResultHandlerException {
	    try {
	        writer.write(str);
	        writer.flush();
        } catch (IOException e) {
        	logger.error("IOException was catched during writing to the stream", e);
			throw new TupleQueryResultHandlerException(e);
        }
    }
}
